package longrise.phone.com.bjjt_henan;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FrameworkManager;
import com.longrise.android.Global;
import com.longrise.android.LFActivity;
import com.longrise.android.LFView;
import com.longrise.android.errorlog.UncaughtException;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.updata.UpdataAPK;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;
import com.umeng.socialize.UMShareAPI;

import longrise.phone.com.bjjt_henan.Constant.MsgConstant;
import longrise.phone.com.bjjt_henan.Constant.URLConstant;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.lunchandlogin.HeNanLoginView;
import longrise.phone.com.bjjt_henan.main.NewMainView;
import longrise.phone.com.bjjt_henan.main.ServiceCenterView;
import longrise.phone.com.bjjt_henan.myaccident.AccidentMainView;
import longrise.phone.com.bjjt_henan.service.LocationService;
import longrise.phone.com.bjjt_henan.tinker.TinkerApplicationLike;
import longrise.phone.com.bjjt_henan.tinker.util.TinkerManager;
import longrise.phone.com.bjjt_henan.tinker.util.Utils;
import longrise.phone.com.bjjt_henan.widget.PromptDialog;

public class MainActivity extends LFActivity implements Callback, UncaughtException.OnExceptionEvent {
    private LinearLayout _bodyView = null;
    private HeNanLoginView _portMenu = null;
    private OnActivityReturnBitmap activityReturnBitmap;
    private PromptDialog dialog;
    private PopupWindow popupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);

            //程序崩溃信息记录，在/baoa_error/log/目录下
            UncaughtException mUncaughtException = UncaughtException.getInstance();
            mUncaughtException.init(this, this.getString(R.string.appRootDir), this);

            this.setAppRootDir(this.getString(R.string.appRootDir));
            // =======================================添加菜单界面==================================
            this._bodyView = this.getBodyView();// 当前框架view
            if (null == this._bodyView)
                return;
            this._bodyView.removeAllViewsInLayout();

            this.setFormMargin(0, 0, 0, 0);// 设置Form的外边距
            if (null == this._portMenu) {
                this._portMenu = new HeNanLoginView(this);
                this._portMenu.init();
            }
            this._portMenu.refresh();
            this._bodyView.addView(this._portMenu.getView(),
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            PackageManager pm = this.getPackageManager();
            if (null != pm) {
                PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);
                if (null != packageInfo) {
                    Global.getInstance().setVersionCode(packageInfo.versionCode);
                    Global.getInstance().setVersionName(packageInfo.versionName);
                }
                packageInfo = null;
            }
            // add by luoyi ================全局参数初始化====================
            this.getAppData().setBaseServerUrl
                    (getResources().getString(R.string.kckpServerUrl));// 周市委基础登录地址外网

            this.getAppData().setServerUrl
                    (getResources().getString(R.string.kckpServerUrl));//快处快赔业务外网地址

            this.getAppData().setUpdateUrl(getResources
                    ().getString(R.string.kckpupdateUrl));// apk升级地址

            //默认地址
            this.getAppData().setLatitude("34.75");
            this.getAppData().setLongitude("113.60");
            this.getAppData().setAddress("河南省郑州市中原区");
            this.getAppData().setDefaultCityCode("179");

            // 检查版本号
            checkVersion();
            registBroadcast();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //获取tinker的application代理类
    public TinkerApplicationLike getAppLike() {
        return (TinkerApplicationLike) TinkerManager.getTinkerApplicationLike();
    }

    //获取数据实体类
    public BaseApplication getAppData() {
        return (getAppLike() == null) ? null : getAppLike().getDataApp();
    }

    /**
     * 检查版本更新
     */
    private void checkVersion() {
        UpdataAPK updataAPK = new UpdataAPK(this, getResources().getString(
                R.string.update_appname), getResources().getString(
                R.string.kckpServerUrl), URLConstant.CHECKVERSION,
                getResources().getString(R.string.updatekey));
        updataAPK.setUpdateUrl(this.getAppData().getUpdateUrl());
        updataAPK.checkVersion();
    }

    /**
     * 注册广播监听是否被挤掉或超时
     */
    private void registBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.longrise.loginForCookId");
        filter.addAction("com.longrise.loginout");
        this.registerReceiver(receiver, filter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String packName = intent.getStringExtra("packageName");
            if (TextUtils.equals(packName, MainActivity.this.getPackageName())) {
                String aciton = intent.getAction();
                if (TextUtils.equals(aciton, "com.longrise.loginout")) {//账号被挤掉
                    showDialog("您的账号已在其他设备登录！");
                } else if (TextUtils.equals(aciton, "com.longrise.loginForCookId")) {//30天未登录
                    showDialog("由于您长时间未使用，请重新登陆验证身份！");
                }
            }
        }
    };

    private void showDialog(String msg) {
        if (null == dialog) {
            dialog = new PromptDialog(this);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancel("返回", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.setConfirm("重新登录", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    //回到登录页
                    FrameworkManager.getInstance().destroyAllForm();
                }
            });
        }
        dialog.setInfo(msg);
        dialog.show();
    }

    //被挤掉后重新登录
    private void againLogin() {
        try {
            DialogUtils.showDialog(this);
            String userflag = (this.getAppData()).getKckpName();
            String pwd = (this.getAppData()).getKckpPass();
            ApiImpI.getInstance(getApplicationContext()).login(userflag, pwd, new ApiImpI.RequestCallBack() {
                @Override
                public void onError(String error) {
                    DialogUtils.closeDialog();
                    if (!TextUtils.isEmpty(error)) {
                        UiUtil.showToast(MainActivity.this, error);
                    }
                }

                @Override
                public void onSuccess(Object result) {
                    DialogUtils.closeDialog();
                    EntityBean bean = (EntityBean) result;
                    String restate = bean.getString("restate");
                    if (TextUtils.equals(restate, "1")) {
                        EntityBean dataBean = bean.getBean("data");
                        if (null != dataBean) {
                            String token = dataBean.getString("token", "");
                            BaseApplication application = getAppData();
                            //缓存数据
                            application.setToken(token);
                            application.setLoginInfo(dataBean);
                            // 将菜单存到本地
                            String userInfoStr = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(dataBean);
                            PrefUtils.setString(MainActivity.this, "loginInfo", userInfoStr);

                            UiUtil.showToast(MainActivity.this, "重新登录成功");
                        }
                    } else {
                        String redes = bean.getString("redes");
                        UiUtil.showToast(MainActivity.this, redes);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initHelpView(View layout, final String caseno) {
        if (layout == null) {
            return;
        }
        //通知的轮播效果
        TextView infoTV = (TextView) layout.findViewById(R.id.tv_help_info);
        if (null != infoTV) {
            infoTV.setSelected(true);
        }
        final View mView = layout.findViewById(R.id.layout_help);
        if (mView != null) {
            mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showHelpPopwindow(mView, caseno);
                }
            });
        }
    }

    private void showHelpPopwindow(View pView, final String caseno) {
        View layout = LayoutInflater.from(this).inflate(R.layout.popwindow_heipview, null);
        layout.findViewById(R.id.help_tv_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (null != popupWindow) {
//                    popupWindow.dismiss();
//                    popupWindow = null;
//                }
                UiUtil.showToast(MainActivity.this, "敬请期待！");
            }
        });
        layout.findViewById(R.id.help_tv_center).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != popupWindow) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                ServiceCenterView view = new ServiceCenterView(MainActivity.this, caseno);
                FrameworkManager.getInstance().showNewForm(MainActivity.this, view);
            }
        });
        popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        //计算向左偏移的距离
        popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int i = popupWindow.getContentView().getMeasuredWidth();
        popupWindow.showAsDropDown(pView, -i + 30, 10);
        popupWindow.update();
    }

    @Override
    public void onResume() {
        super.onResume();
        Utils.setBackground(false);
        LSMsgCall(MsgConstant.RESUME, "onresume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Utils.setBackground(true);
    }

    @Override
    protected void onDestroy() {
        if (null != this._bodyView) {
            this._bodyView.removeAllViewsInLayout();
        }
        this._bodyView = null;

        if (Global.getInstance() != null) {
            Global.getInstance().onDistory();
        }
        DialogUtils.destroyDialog();
        this.unregisterReceiver(receiver);
        UMShareAPI.get(this).release();
        stopService(new Intent(this, LocationService.class));
        super.onDestroy();// 此句必须放最后

        System.exit(0);
    }

    /**
     * handle回调方法
     */
    @Override
    public boolean handleMessage(Message message) {
        return false;
    }

    public void setOnActivityReturnBitmap(OnActivityReturnBitmap oarb) {
        this.activityReturnBitmap = oarb;
    }

    @Override
    public void onExecption(String exception) {

    }

    public interface OnActivityReturnBitmap {
        public void activityReturnBitmap(int requestCode, int resultCode, Intent data);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (null != activityReturnBitmap) {
            this.activityReturnBitmap.activityReturnBitmap(requestCode, resultCode, data);
        }
    }

    /**
     * 回到主界面或历史案件界面，销毁无用的流程界面
     */
    public void backToMainView() {
        LFView view = null;
        boolean isHistroy = PrefUtils.getBoolean(this, MsgConstant.HISTORY_CASE, false);
        int level = -1;
        if (isHistroy) {//回到历史案件列表
            level = (getAppLike()).getHistroyLevel();
            view = new AccidentMainView(this);
        } else {//回到主界面
            level = (getAppLike()).getMainLevel();
            view = new NewMainView(this);
            ((NewMainView) view).setBack(true);
        }
        FrameworkManager.getInstance().showForm(this, view, level);
    }


    //权限回调处理
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MsgConstant.PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//用户同意授权
                if (TextUtils.equals(permissions[0], Manifest.permission.ACCESS_FINE_LOCATION)) {
                    LSMsgCall(MsgConstant.PERMISSION, "PERMISSION_GRANTED");
                }
            } else {//用户不同意
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {//被拒绝

                } else {//勾选不再提醒
                    String permission = null;
                    if (TextUtils.equals(permissions[0], android.Manifest.permission.CAMERA)) {
                        permission = getString(R.string.crmerastate);
                    } else if (TextUtils.equals(permissions[0], Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        permission = getString(R.string.storgestate);
                    } else if (TextUtils.equals(permissions[0], Manifest.permission.ACCESS_FINE_LOCATION)) {
                        permission = getString(R.string.locationstate);
                    } else if (TextUtils.equals(permissions[0], Manifest.permission.CALL_PHONE)) {
                        permission = getString(R.string.phonestate);
                    }
                    PermissionHelper.showPermissionDialog(this, permission, false);
                }
            }
        }
    }
}
